﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ExampleSCPlayerController : MonoBehaviour
{

    private GameObject controlPanelGObj;
    private Button[] settingBtns;
    private GameObject[] settingPanels;
    private SCPlayer scplayer;
    private Button pauseBtn;
    private Selectable[] selectables;
    private Toggle openAutoPlayToggle;
    private Slider seekSlider;
    private bool isPress = false;
    private Text videoPacketCountText, videoFrameCountText;
    private Text audioPacketCountText, audioFrameCountText;
    private Text currentTimeText, totalTimeText;
    private ExampleTipPanel tipPanel;
    private InputField urlInput;
    private SampleComboBox formatPriorityComboBox;
    // Use this for initialization
    void Start()
    {
        scplayer = GetComponent<SCPlayer>();

        controlPanelGObj = transform.Find("ControlPanel").gameObject;
        transform.Find("ControlPanleButton").GetComponent<Button>().onClick.AddListener(() => { controlPanelGObj.SetActive(!controlPanelGObj.activeSelf); });
        controlPanelGObj.SetActive(false);

        transform.Find("ControlPanel/OpenModelPanel/URLToggle").GetComponent<Toggle>().isOn = scplayer.openModel == OpenModel.URL ? true : false;
        transform.Find("ControlPanel/OpenModelPanel/CameraToggle").GetComponent<Toggle>().isOn = scplayer.openModel == OpenModel.URL ? false : true;

        transform.Find("ControlPanel/OpenModelPanel/URLToggle").GetComponent<Toggle>().onValueChanged.AddListener((isOn) => { scplayer.openModel = isOn ? OpenModel.URL : OpenModel.Camera; });

        settingBtns = new Button[3];
        settingBtns[0] = controlPanelGObj.transform.Find("SettingPagePanel/BaseButton").GetComponent<Button>();
        settingBtns[1] = controlPanelGObj.transform.Find("SettingPagePanel/CameraButton").GetComponent<Button>();
        settingBtns[2] = controlPanelGObj.transform.Find("SettingPagePanel/OtherButton").GetComponent<Button>();

        settingPanels = new GameObject[3];
        settingPanels[0] = controlPanelGObj.transform.Find("SettingPagePanel/BasePanel").gameObject;
        settingPanels[1] = controlPanelGObj.transform.Find("SettingPagePanel/CameraPanel").gameObject;
        settingPanels[2] = controlPanelGObj.transform.Find("SettingPagePanel/OtherPanel").gameObject;

        for (int i = 0; i < settingBtns.Length; i++)
        {
            settingBtns[i].onClick.AddListener(OnSelectPage);
            settingBtns[i].GetComponent<Image>().color = Color.white;
            //if (i > 0)
            //    settingPanels[i].SetActive(false);
            //else
            settingPanels[i].SetActive(true);

        }
        settingBtns[0].GetComponent<Image>().color = settingPanels[0].GetComponent<Image>().color;



        controlPanelGObj.transform.Find("DynamicControl/OpenButton").GetComponent<Button>().onClick.AddListener(OnOpenClicked);
        pauseBtn = controlPanelGObj.transform.Find("DynamicControl/PauseButton").GetComponent<Button>();
        pauseBtn.onClick.AddListener(OnPauseClicked);
        controlPanelGObj.transform.Find("DynamicControl/CloseButton").GetComponent<Button>().onClick.AddListener(OnCloseClicked);

        urlInput = controlPanelGObj.transform.Find("URLPanel/UrlInputField").GetComponent<InputField>();
        urlInput.text = scplayer.url;
        urlInput.onValueChanged.AddListener((value) => { scplayer.url = value; });

        #region setting before open
        InputField openTimeoutInput = controlPanelGObj.transform.Find("SettingPagePanel/BasePanel/OpenTimeoutInputField").GetComponent<InputField>();
        openTimeoutInput.text = scplayer.openTimeout.ToString();
        int defaultOpenTimeoutValue = scplayer.openTimeout;
        openTimeoutInput.onValueChanged.AddListener((value) => { scplayer.openTimeout = SCUtility.String2Int(value, defaultOpenTimeoutValue); });

        InputField readTimeoutInput = controlPanelGObj.transform.Find("SettingPagePanel/BasePanel/ReadTimeoutInputField").GetComponent<InputField>();
        readTimeoutInput.text = scplayer.readTimeout.ToString();
        int defaultReadTimeoutValue = scplayer.readTimeout;
        readTimeoutInput.onValueChanged.AddListener((value) => { scplayer.readTimeout = SCUtility.String2Int(value, defaultReadTimeoutValue); });

        Toggle enableAudoToggle = controlPanelGObj.transform.Find("SettingPagePanel/BasePanel/EnableAudioToggle").GetComponent<Toggle>();
        enableAudoToggle.isOn = scplayer.enableAudio;
        enableAudoToggle.onValueChanged.AddListener((value) => { scplayer.enableAudio = value; });

        Toggle enableVideoToggle = controlPanelGObj.transform.Find("SettingPagePanel/BasePanel/EnableVideoToggle").GetComponent<Toggle>();
        enableVideoToggle.isOn = scplayer.enableVideo;
        enableVideoToggle.onValueChanged.AddListener((value) => { scplayer.enableVideo = value; });

        InputField cameraWidthInput = controlPanelGObj.transform.Find("SettingPagePanel/CameraPanel/CameraWidthInputField").GetComponent<InputField>();
        cameraWidthInput.text = scplayer.cameraWidth.ToString();
        int defaultCameraWidthValue = scplayer.cameraWidth;
        cameraWidthInput.onValueChanged.AddListener((value) => { scplayer.cameraWidth = SCUtility.String2Int(value, defaultCameraWidthValue); });

        InputField cameraHeightInput = controlPanelGObj.transform.Find("SettingPagePanel/CameraPanel/CameraHeightInputField").GetComponent<InputField>();
        cameraHeightInput.text = scplayer.cameraHeight.ToString();
        int defaultCameraHeightValue = scplayer.cameraHeight;
        cameraHeightInput.onValueChanged.AddListener((value) => { scplayer.cameraHeight = SCUtility.String2Int(value, defaultCameraHeightValue); });

        InputField frameRateInput = controlPanelGObj.transform.Find("SettingPagePanel/CameraPanel/FrameRateInputField").GetComponent<InputField>();
        frameRateInput.text = scplayer.cameraFrameRate.ToString();
        int defaultFrameRateValue = scplayer.cameraFrameRate;
        frameRateInput.onValueChanged.AddListener((value) => { scplayer.cameraFrameRate = SCUtility.String2Int(value, defaultFrameRateValue); });

        formatPriorityComboBox = controlPanelGObj.transform.Find("SettingPagePanel/CameraPanel/FormatPriorityComboBox").GetComponent<SampleComboBox>();
        formatPriorityComboBox.SetCurrentItem(scplayer.cameraInputPriority.ToString());
        formatPriorityComboBox.OnValueChanged((value) =>
        {
            CIFP cifp = (CIFP)System.Enum.Parse(typeof(CIFP), value);
            scplayer.cameraInputPriority = cifp;
        });

        controlPanelGObj.transform.Find("SettingPagePanel/CameraPanel/CameraInfoBtn").GetComponent<Button>().onClick.AddListener(OnCameraInfoClicked);

        Toggle cfld = controlPanelGObj.transform.Find("SettingPagePanel/OtherPanel/CodecForceLowDelayToggle").GetComponent<Toggle>();
        cfld.isOn = scplayer.codecForceLowDelay;
        cfld.onValueChanged.AddListener((value) => { scplayer.codecForceLowDelay = value; });

        Toggle nb = controlPanelGObj.transform.Find("SettingPagePanel/OtherPanel/NoBufferToggle").GetComponent<Toggle>();
        nb.isOn = scplayer.nobuffer;
        nb.onValueChanged.AddListener((value) => { scplayer.nobuffer = value; });

        Toggle fns = controlPanelGObj.transform.Find("SettingPagePanel/OtherPanel/ForceNoSyncToggle").GetComponent<Toggle>();
        fns.isOn = scplayer.nosync;
        fns.onValueChanged.AddListener((value) => { scplayer.nosync = value; });

        Toggle rtp = controlPanelGObj.transform.Find("SettingPagePanel/OtherPanel/RTSPTransportToggle").GetComponent<Toggle>();
        rtp.isOn = scplayer.rtspTransportType == RtspTransportType.TCP ? true : false;
        rtp.onValueChanged.AddListener((value) => { scplayer.rtspTransportType = value ? RtspTransportType.TCP : RtspTransportType.UDP; });

        SampleComboBox opf = controlPanelGObj.transform.Find("SettingPagePanel/OtherPanel/OutputPixelFormatComboBox").GetComponent<SampleComboBox>();
        opf.SetCurrentItem(scplayer.outpixfmt.ToString().Remove(0, 8));
        opf.OnValueChanged((value) =>
        {
            OutPixFmt fmt = (OutPixFmt)System.Enum.Parse(typeof(OutPixFmt), "PIX_FMT_" + value);
            scplayer.outpixfmt = fmt;
        });
        #endregion //setting before open

        #region setting dynamic
        Toggle loopToogle = controlPanelGObj.transform.Find("DynamicControl/LoopToggle").GetComponent<Toggle>();
        loopToogle.isOn = scplayer.isLoop;
        loopToogle.onValueChanged.AddListener((value) => { scplayer.isLoop = value; });

        openAutoPlayToggle = controlPanelGObj.transform.Find("DynamicControl/OpenAutoPlayToggle").GetComponent<Toggle>();
        openAutoPlayToggle.isOn = scplayer.openAutoPlay;
        openAutoPlayToggle.onValueChanged.AddListener((value) => { scplayer.openAutoPlay = value; });


        Slider volumeSlider = controlPanelGObj.transform.Find("DynamicControl/VolumeSlider").GetComponent<Slider>();
        volumeSlider.value = scplayer.volume;
        volumeSlider.onValueChanged.AddListener((value) => { scplayer.volume = value; });

        controlPanelGObj.transform.Find("DynamicControl/ApplyButton").GetComponent<Button>().onClick.AddListener(() =>
        {
            int index = SCUtility.String2Int(controlPanelGObj.transform.Find("DynamicControl/AudioTrackInputField").GetComponent<InputField>().text, 0);
            scplayer.Control.SetAudioTrack(index);
        });


        controlPanelGObj.transform.Find("DynamicControl/StreamInfoButton").GetComponent<Button>().onClick.AddListener(OnStreamInfoClicked);

        videoPacketCountText = controlPanelGObj.transform.Find("DynamicControl/VideoPacketCountText").GetComponent<Text>();

        videoFrameCountText = controlPanelGObj.transform.Find("DynamicControl/VideoFrameCountText").GetComponent<Text>();

        audioPacketCountText = controlPanelGObj.transform.Find("DynamicControl/AudioPacketCountText").GetComponent<Text>();

        audioFrameCountText = controlPanelGObj.transform.Find("DynamicControl/AudioFrameCountText").GetComponent<Text>();

        currentTimeText = controlPanelGObj.transform.Find("DynamicControl/CurrentTimeText").GetComponent<Text>();
        totalTimeText = controlPanelGObj.transform.Find("DynamicControl/TotalTimeText").GetComponent<Text>();

        seekSlider = controlPanelGObj.transform.Find("DynamicControl/SeekSlider").GetComponent<Slider>();
        #endregion //setting dynamic

        selectables = controlPanelGObj.transform.Find("SettingPagePanel").GetComponentsInChildren<Selectable>();

        for (int i = 0; i < settingBtns.Length; i++)
            if (i > 0)
                settingPanels[i].SetActive(false);

        tipPanel = transform.Find("TipPanel").GetComponent<ExampleTipPanel>();

        scplayer.OnOpenResultEvent += OnOpenResult;
        scplayer.OnInterruptEvent += OnInterrupt;
        scplayer.OnCreateCanvasFailedEvent += OnCreateCanvasFailed;
    }

    private void OnDestroy()
    {
        scplayer.OnOpenResultEvent -= OnOpenResult;
        scplayer.OnInterruptEvent -= OnInterrupt;
        scplayer.OnCreateCanvasFailedEvent -= OnCreateCanvasFailed;
    }
    private void OnOpenResult(StreamsParameters sp)
    {
        if(sp.retcode != RetcodeType.Success)
        {
            tipPanel.MessageTip(LogLevel.LEVEL_WARNING, "Open Failed", sp.errLog);
            return;
        }
        if (sp.audioStream == null) return;
        string str = "";
        for (int i = 0; i < sp.audioStream.streamCount; i++)
        {
            if (i > 0) str += ',';
            str += i.ToString();
        }
        controlPanelGObj.transform.Find("DynamicControl/AudioTrackInputField/Placeholder").GetComponent<Text>().text = str;
    }

    private void OnInterrupt(InterruptCode code)
    {
        tipPanel.MessageTip(LogLevel.LEVEL_WARNING, "Interrupt", code.ToString());
    }

    private void OnCreateCanvasFailed(string msg)
    {
        tipPanel.MessageTip(LogLevel.LEVEL_WARNING, "Canvas not support!", msg);
    }
    private void OnSelectPage()
    {
        var button = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject;
        int index = -1;
        //Color color = settingPanels[0].GetComponent<Image>().color;
        for (int i = 0; i < settingBtns.Length; i++)
        {
            if (button.name == settingBtns[i].gameObject.name)
                index = i;
            settingBtns[i].GetComponent<Image>().color = Color.white;
            settingPanels[i].SetActive(false);
        }
        settingPanels[index].SetActive(true);
        settingBtns[index].GetComponent<Image>().color = settingPanels[0].GetComponent<Image>().color;
    }

    private void OnOpenClicked()
    {

        for (int i = 0; i < selectables.Length; i++)
            selectables[i].interactable = false;
        pauseBtn.GetComponentInChildren<Text>().text = openAutoPlayToggle.isOn ? "Pause" : "Play";
        scplayer.Open();
    }
    private void OnPauseClicked()
    {
        if (scplayer.IsPause)
        {
            pauseBtn.GetComponentInChildren<Text>().text = "Pause";
            scplayer.Play();

        }
        else
        {
            pauseBtn.GetComponentInChildren<Text>().text = "Play";
            scplayer.Pause();
        }
    }
    private void OnCloseClicked()
    {
        for (int i = 0; i < selectables.Length; i++)
            selectables[i].interactable = true;
        scplayer.Close();
    }

    public void OnSeekSliderPointerDown()
    {
        isPress = true;
    }
    public void OnSeekSliderPointerUp()
    {
        isPress = false;
        scplayer.Seek(seekSlider.value);
    }

    private void OnCameraInfoClicked()
    {
         CameraDescription cd = scplayer.Control.GetCameraInfo(urlInput.text);
        formatPriorityComboBox.ClearItem();
        formatPriorityComboBox.AddItem(CIFP.AUTO.ToString());
        if (cd.supportYUYV422) formatPriorityComboBox.AddItem(CIFP.YUYV422.ToString());
        if (cd.supportMJPEG) formatPriorityComboBox.AddItem(CIFP.MJPEG.ToString());
        if (cd.supportNV12) formatPriorityComboBox.AddItem(CIFP.NV12.ToString());
        if (cd.supportBGR0) formatPriorityComboBox.AddItem(CIFP.BGR0.ToString());

        string info = "========== All Camera List ==========\n";
        WebCamDevice[] devices = WebCamTexture.devices;
        for (int i = 0; i < devices.Length; i++)
        {
            info += devices[i].name;
            info += "\n";
        }
        info += "=====================================\n\n";
        info += string.Format("========== {0} ==========\n", urlInput.text);
        info += cd.desc;
        info += "=====================================\n";

        tipPanel.MessageTip(LogLevel.LEVEL_INFO, "CameraDescribe", info);

    }
    private void OnStreamInfoClicked()
    {
        tipPanel.MessageTip(LogLevel.LEVEL_INFO, "MediaDescribe", scplayer.Control.MediaDescribe);
    }
    // Update is called once per frame
    void Update()
    {
        PFCounts counts = scplayer.Control.GetPFCounts();
        if(counts != null)
        {
            videoPacketCountText.text = counts.videoPktCount.ToString();
            videoFrameCountText.text = counts.videoFrameCount.ToString();
            audioPacketCountText.text = counts.audioPktCount.ToString();
            audioFrameCountText.text = counts.audioFrameCount.ToString();
        }
       
        if (!isPress)
        {
            seekSlider.value = (float)scplayer.Control.GetCurrentProgress();
        }


        currentTimeText.text = SCUtility.Int2Time((int)(scplayer.TotalMs * scplayer.Control.GetCurrentProgress()));
        totalTimeText.text = SCUtility.Int2Time((int)scplayer.TotalMs);

        if(Input.GetKeyDown(KeyCode.Escape))
        {
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;

#else
            Application.Quit();
#endif
        }
    }
}
